package com.hmall.gateway.filters;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor //利用注解生成构造器，注入bean对象
public class AuthGllobalFilter implements GlobalFilter , Ordered {
    private final AuthProperties authProperties;
    private final JwtTool jwtTool;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();//spring提供的路径匹配器
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request
        ServerHttpRequest request = exchange.getRequest();
        //判断是否需要进行登录拦截
        if(isExcludde(request.getPath().toString())){
            //放行
            return chain.filter(exchange);
        }
        //获取token
        String token=null;
        List<String> headers = request.getHeaders().get("authorization");//jwt令牌默认保存到key为authorization的请求头中
        if(headers != null &&!headers.isEmpty()){
            token=headers.get(0);
        }

        //校验并解析token，获取用户信息
        Long userId=null;
        try {
             userId= jwtTool.parseToken(token);
        } catch (Exception e) {
            //拦截，设置状态响应码
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //终止，后续拦截器不会执行了
            return response.setComplete();
        }
        //TODO 传递用户信息
        String userInfo=userId.toString();
        ServerWebExchange swe = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();
        //放行
        return  chain.filter(swe);
    }

    //判断路径是否存在
    private boolean isExcludde(String path) {
        for(String pathPattern:authProperties.getExcludePaths()){
            if(antPathMatcher.match(pathPattern, path)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
